import pandas as pd
from aiogram import types
from aiogram_dialog import DialogManager
from fluentogram import TranslatorRunner

from src.core.exporters.products_to_xlsx import export_products_to_xlsx
from src.core.utils.date_time import get_date_time
from src.database.services.category import CategoryService
from src.database.services.order import OrderService


async def export_order_products_to_xlsx(
    call: types.CallbackQuery, _, manager: DialogManager
):
    locale: TranslatorRunner = manager.middleware_data.get("locale")
    order_id: int = manager.dialog_data.get("order_id")
    order_service: OrderService = manager.middleware_data.get("order_service")
    category_service: CategoryService = manager.middleware_data.get("category_service")

    order = await order_service.get_order_by_id(order_id, joined=True)

    if len(order.products) > 0:
        category_id = order.products[0].category_id
        category = await category_service.get_category_by_id(category_id)
        xlsx_content = export_products_to_xlsx(order.products, category.name)

        cur_date = get_date_time(time_format="%Y-%m-%d_%H-%M-%S")
        await call.message.answer_document(
            types.BufferedInputFile(
                xlsx_content,
                filename=f"Accounts {cur_date}.xlsx",
            ),
            caption=locale.get("excel-info-msg"),
        )
    else:
        await call.answer(locale.get("no-products-in-order"))
